import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { baziAnalysis } from '../../services/bazi';

const BaziAnalysis: React.FC = () => {
  const [year, setYear] = useState<number | undefined>();
  const [month, setMonth] = useState<number | undefined>();
  const [day, setDay] = useState<number | undefined>();
  const [hour, setHour] = useState<number | undefined>();
  const [gender, setGender] = useState<number>(1); // 默认男性
  const [name, setName] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  
  const navigate = useNavigate();
  
  // 生成年份选项
  const yearOptions = [];
  const currentYear = new Date().getFullYear();
  for (let i = currentYear; i >= 1900; i--) {
    yearOptions.push(i);
  }
  
  // 生成月份选项
  const monthOptions = [];
  for (let i = 1; i <= 12; i++) {
    monthOptions.push(i);
  }
  
  // 生成日期选项
  const dayOptions = [];
  const daysInMonth = year && month ? new Date(year, month, 0).getDate() : 31;
  for (let i = 1; i <= daysInMonth; i++) {
    dayOptions.push(i);
  }
  
  // 生成小时选项
  const hourOptions = [];
  for (let i = 0; i <= 23; i++) {
    hourOptions.push(i);
  }
  
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 表单验证
    if (!year || !month || !day) {
      setError('请选择完整的出生年月日');
      return;
    }
    
    try {
      setLoading(true);
      setError('');
      
      // 调用八字分析API
      const response = await baziAnalysis({
        year,
        month,
        day,
        hour,
        gender,
        name: name || undefined
      });
      
      if (response.code === 200) {
        // 分析成功，跳转到详情页
        navigate(`/bazi/${response.data.baziId}`);
      } else {
        setError(response.message || '分析失败');
      }
    } catch (err: any) {
      setError(err.message || '分析失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md mx-auto bg-white rounded-xl shadow-md overflow-hidden md:max-w-2xl p-6">
        <div className="text-center mb-8">
          <h2 className="text-2xl font-bold text-gray-900">生辰八字分析</h2>
          <p className="mt-2 text-sm text-gray-600">
            请输入您的出生年月日时，获取专业的八字分析
          </p>
        </div>
        
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
            <div>
              <label htmlFor="name" className="block text-sm font-medium text-gray-700">
                姓名（选填）
              </label>
              <input
                type="text"
                id="name"
                className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                value={name}
                onChange={(e) => setName(e.target.value)}
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700">
                性别
              </label>
              <div className="mt-1 flex space-x-4">
                <div className="flex items-center">
                  <input
                    id="male"
                    name="gender"
                    type="radio"
                    checked={gender === 1}
                    onChange={() => setGender(1)}
                    className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300"
                  />
                  <label htmlFor="male" className="ml-2 block text-sm text-gray-700">
                    男
                  </label>
                </div>
                <div className="flex items-center">
                  <input
                    id="female"
                    name="gender"
                    type="radio"
                    checked={gender === 2}
                    onChange={() => setGender(2)}
                    className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300"
                  />
                  <label htmlFor="female" className="ml-2 block text-sm text-gray-700">
                    女
                  </label>
                </div>
              </div>
            </div>
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700">
              出生日期
            </label>
            <div className="mt-1 grid grid-cols-4 gap-2">
              <select
                className="block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                value={year || ''}
                onChange={(e) => setYear(e.target.value ? parseInt(e.target.value) : undefined)}
              >
                <option value="">年</option>
                {yearOptions.map(y => (
                  <option key={y} value={y}>{y}年</option>
                ))}
              </select>
              
              <select
                className="block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                value={month || ''}
                onChange={(e) => setMonth(e.target.value ? parseInt(e.target.value) : undefined)}
              >
                <option value="">月</option>
                {monthOptions.map(m => (
                  <option key={m} value={m}>{m}月</option>
                ))}
              </select>
              
              <select
                className="block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                value={day || ''}
                onChange={(e) => setDay(e.target.value ? parseInt(e.target.value) : undefined)}
              >
                <option value="">日</option>
                {dayOptions.map(d => (
                  <option key={d} value={d}>{d}日</option>
                ))}
              </select>
              
              <select
                className="block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                value={hour !== undefined ? hour : ''}
                onChange={(e) => setHour(e.target.value ? parseInt(e.target.value) : undefined)}
              >
                <option value="">时（选填）</option>
                {hourOptions.map(h => (
                  <option key={h} value={h}>{h}时</option>
                ))}
              </select>
            </div>
          </div>
          
          {error && (
            <div className="text-red-500 text-sm text-center">
              {error}
            </div>
          )}
          
          <div>
            <button
              type="submit"
              disabled={loading}
              className={`w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${loading ? 'opacity-70 cursor-not-allowed' : ''}`}
            >
              {loading ? '分析中...' : '开始分析'}
            </button>
          </div>
          
          <div className="text-xs text-gray-500 text-center">
            注：未登录用户每次分析需支付1.1元，登录用户0.1元/次，VIP会员无限使用
          </div>
        </form>
      </div>
    </div>
  );
};

export default BaziAnalysis;
